//
//  database_util.swift
//  core_data_demo
//
//  Created by 李威 on 2022/2/18.
/*
 getObj拿到对象 进行增删改查操作完 save保存
 */
import UIKit
import CoreData
class CoreDataUtil {
/*
 context.undoManager = nil
 context.automaticallyMergesChangesFromParent = true
 */
    static let container = CoreDataUtil.getContainer()
//    private var persistentContainer : NSPersistentContainer
//    static func regist(persistentContainer: NSPersistentContainer) {
//
//    }
    static func getContainer() -> NSPersistentContainer{
        let container = NSPersistentContainer(name: "core_data_demo")
        let options = [
            NSMigratePersistentStoresAutomaticallyOption:true,
            NSInferMappingModelAutomaticallyOption: true
        ]
        do {
            try container.persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: nil, options: options)
        } catch let error {
            fatalError("error \(error)")
        }
        
        
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }
    //
    static func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
        container.performBackgroundTask { (ctx) in
            block(ctx)
            if ctx.hasChanges {
                do {
                    try ctx.save()
                } catch let error {
                    fatalError("save error: \(error)")
                }
            }
        }
    }
    
    //获取对象
    static func getObj<T:NSManagedObject>(oType:T.Type) -> T?{
        let context = container.viewContext
        let name = "\(oType.self)"
        let model = NSEntityDescription.insertNewObject(forEntityName: name, into: context) as? T
        return model
    }
    //保存操作
    static func save<T:NSManagedObject>(model:inout T){
        let context = container.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch let error {
                fatalError("save error: \(error)")
            }
        }
    }
    //获取实体集合
    static func fetch<T:NSManagedObject>(oType:T.Type, predicates:[NSPredicate]? = nil) -> [T]? {
        let context = container.viewContext
        let name = "\(oType.self)"
//        let req: NSFetchRequest<T> = User.fetchRequest()
//        req.sortDescriptors = [NSSortDescriptor(key: #keyPath(), ascending: false)] //搜索排序

        if let request:NSFetchRequest<T> = NSFetchRequest<T>(entityName: name) as? NSFetchRequest<T> {
//            request.fetchLimit = 10//查询结果数量
//            request.fetchOffset = 0//查询偏移量
            if (predicates?.count) != nil {
                //request.predicate = predi////一个查询条件时直接设置
                request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates!)//设置多个查询条件
            }
            if let resultList = try? context.fetch(request) {
                return resultList
            }
        }
        return nil
    }
}

//版本升级
/*
 editor -> add model version 自动添加 core_data_demo2
 在core_data_demo2选择实体，右侧model version切换版本，绿色对号为当前版本
 */
